package com.improve.frame.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.improve.frame.db.mapper.BaseMapper;
import com.improve.frame.db.properties.MybatisPlusAutoFillProperties;
import com.improve.frame.db.properties.TenantProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @Description
 *      mybatis-plus自动配置
 * @Author wzxing918
 * @Date 2021-03-31
 * @Version 1.0.0
 **/
@EnableConfigurationProperties(MybatisPlusAutoFillProperties.class)
@EnableTransactionManagement
@MapperScan(value = {"com.improve.frame.jdbc.mapper", "com.improve.frame.jdbc.mapper"}, markerInterface = BaseMapper.class)
public class MybatisPlusAutoConfigure {
    @Autowired
    private TenantProperties tenantProperties;

    @Autowired
    private MybatisPlusAutoFillProperties autoFillProperties;

    @Autowired
    private TenantLineHandler tenantLineHandler;

    /**
     * 分页插件
     * @return 分页拦截器
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

        mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        boolean enableTenant = tenantProperties.getEnable();
        if (enableTenant) {
            TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor();
            tenantLineInnerInterceptor.setTenantLineHandler(tenantLineHandler);
            mybatisPlusInterceptor.addInnerInterceptor(tenantLineInnerInterceptor);
        }
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());

        return mybatisPlusInterceptor;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "improve.mybatis-plus.auto-fill", name = "enabled", havingValue = "true", matchIfMissing = true)
    public MetaObjectHandler metaObjectHandler() {
        return new DateMetaObjectHandler(autoFillProperties);
    }
}
